#include <linux/err.h>
#include <linux/bug.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/errno.h>
#include <linux/highmem.h>
#include <linux/stat.h>
#include "ext2.h"

typedef struct ext2_dir_entry_2 ext2_dirent;

#define S_SHIFT 12
static unsigned char ext2_type_by_mode[S_IFMT >> S_SHIFT] = {
	[S_IFREG >> S_SHIFT]	= EXT2_FT_REG_FILE,
	[S_IFDIR >> S_SHIFT]	= EXT2_FT_DIR,
	[S_IFCHR >> S_SHIFT]	= EXT2_FT_CHRDEV,
	[S_IFBLK >> S_SHIFT]	= EXT2_FT_BLKDEV,
	[S_IFIFO >> S_SHIFT]	= EXT2_FT_FIFO,
	[S_IFSOCK >> S_SHIFT]	= EXT2_FT_SOCK,
	[S_IFLNK >> S_SHIFT]	= EXT2_FT_SYMLINK,
};

static inline void ext2_set_de_type(ext2_dirent *de, struct inode *inode)
{
	mode_t mode = inode->i_mode;
	if (EXT2_HAS_INCOMPAT_FEATURE(inode->i_sb, EXT2_FEATURE_INCOMPAT_FILETYPE))
		de->file_type = ext2_type_by_mode[(mode & S_IFMT)>>S_SHIFT];
	else
		de->file_type = 0;
}

static inline __le16 ext2_rec_len_to_disk(unsigned len)
{
	if (len == (1 << 16))
		return cpu_to_le16(EXT2_MAX_REC_LEN);
	else
		BUG_ON(len > (1 << 16));
	return cpu_to_le16(len);
}

static inline unsigned long dir_pages(struct inode *inode)
{
	return (inode->i_size+PAGE_CACHE_SIZE-1)>>PAGE_CACHE_SHIFT;
}

static int ext2_commit_chunk(struct page *page, loff_t pos, unsigned len)
{
	struct address_space *mapping = page->mapping;
	struct inode *dir = mapping->host;
	int err = 0;

	printf("this is %s(): %d\r\n", __func__, __LINE__);

	dir->i_version++;
	block_write_end(NULL, mapping, pos, len, len, page, NULL);

	printf("this is %s(): %d >>> pos = %d\r\n", __func__, __LINE__, pos);
	printf("this is %s(): %d >>> len = %d\r\n", __func__, __LINE__, len);
	printf("this is %s(): %d >>> dir->i_size = %d\r\n", __func__, __LINE__, dir->i_size);
	if (pos+len > dir->i_size) {
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		i_size_write(dir, pos+len);
		// mark_inode_dirty(dir);
	}

	// if (IS_DIRSYNC(dir)) {
	// 	err = write_one_page(page, 1);
	// 	if (!err)
	// 		err = ext2_sync_inode(dir);
	// } else {
		// unlock_page(page);
	// }

	printf("this is %s(): %d\r\n", __func__, __LINE__);
	return err;
}

static inline unsigned ext2_chunk_size(struct inode *inode)
{
	return inode->i_sb->s_blocksize;
}

static inline int ext2_match(int len, const char * const name,
					struct ext2_dir_entry_2 * de)
{
	if (len != de->name_len)
		return 0;
	if (!de->inode)
		return 0;
	return !memcmp(name, de->name, len);
}

static struct page * ext2_get_page(struct inode *dir, unsigned long n,
				   int quiet)
{
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	struct address_space *mapping = dir->i_mapping;
	printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
	struct page *page = read_mapping_page(mapping, n, NULL);
	printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
	// if (!IS_ERR(page)) {
	// 	kmap(page);
	// 	if (!PageChecked(page))
	// 		ext2_check_page(page, quiet);
	// 	if (PageError(page))
	// 		goto fail;
	// }
	return page;

fail:
	// ext2_put_page(page);
	return ERR_PTR(-EIO);
}

static unsigned ext2_last_byte(struct inode *inode, unsigned long page_nr)
{
	unsigned last_byte = inode->i_size;

	last_byte -= page_nr << PAGE_CACHE_SHIFT;
	if (last_byte > PAGE_CACHE_SIZE)
		last_byte = PAGE_CACHE_SIZE;
	return last_byte;
}

static inline unsigned ext2_rec_len_from_disk(__le16 dlen)
{
	unsigned len = le16_to_cpu(dlen);

	if (len == EXT2_MAX_REC_LEN)
		return 1 << 16;
	return len;
}

static inline ext2_dirent *ext2_next_entry(ext2_dirent *p)
{
	printf("this is %s(): %d >>> p->rec_len = %d\r\n", __func__, __LINE__, p->rec_len);
	printf("this is %s(): %d >>> ext2_rec_len_from_disk(p->rec_len) = %d\r\n", __func__, __LINE__, ext2_rec_len_from_disk(p->rec_len));
	return (ext2_dirent *)((char *)p + ext2_rec_len_from_disk(p->rec_len));
}

struct ext2_dir_entry_3 *g_de = NULL;

int ext2_add_link(struct dentry *dentry, struct inode *inode)
{
	struct inode *dir = dentry->d_parent->d_inode;
	const char *name = dentry->d_name.name;
	int namelen = dentry->d_name.len;
	unsigned chunk_size = ext2_chunk_size(dir);
	unsigned reclen = EXT2_DIR_REC_LEN(namelen);
	unsigned short rec_len, name_len;
	struct page *page = NULL;
	ext2_dirent * de;
	unsigned long npages = dir_pages(dir);
	unsigned long n;
	char *kaddr;
	loff_t pos;
	int err;

	printf("this is %s(): %d\r\n", __func__, __LINE__);

	/*
	 * We take care of directory expansion in the same loop.
	 * This code plays outside i_size, so it locks the page
	 * to protect that region.
	 */
	for (n = 0; n <= npages; n++) {
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		char *dir_end;

		page = ext2_get_page(dir, n, 0);
		err = PTR_ERR(page);
		if (IS_ERR(page))
			goto out;
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		// lock_page(page);
		kaddr = page_address(page);
		dir_end = kaddr + ext2_last_byte(dir, n);
		de = (ext2_dirent *)kaddr;
		kaddr += PAGE_CACHE_SIZE - reclen;
		while ((char *)de <= kaddr) {
			printf("this is %s(): %d >>> de->name = %s\r\n", __func__, __LINE__, de->name);
			if ((char *)de == dir_end) {
				printf("this is %s(): %d\r\n", __func__, __LINE__);
				/* We hit i_size */
				name_len = 0;
				rec_len = chunk_size;
				de->rec_len = ext2_rec_len_to_disk(chunk_size);
				de->inode = 0;
				goto got_it;
			}
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			if (de->rec_len == 0) {
				printf("this is %s(): %d\r\n", __func__, __LINE__);
				ext2_error(dir->i_sb, __func__,
					"zero-length directory entry");
				err = -EIO;
				goto out_unlock;
			}
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			err = -EEXIST;
			if (ext2_match(namelen, name, de))
				goto out_unlock;
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			name_len = EXT2_DIR_REC_LEN(de->name_len);
			rec_len = ext2_rec_len_from_disk(de->rec_len);
			if (!de->inode && rec_len >= reclen)
				goto got_it;
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			if (rec_len >= name_len + reclen)
				goto got_it;
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			de = (ext2_dirent *) ((char *) de + rec_len);
		}
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		// unlock_page(page);
		// ext2_put_page(page);
	}
	// BUG();
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	return -EINVAL;

got_it:
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	pos = page_offset(page) +
		(char*)de - (char*)page_address(page);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	err = __ext2_write_begin(NULL, page->mapping, pos, rec_len, 0,
							&page, NULL);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	if (err)
		goto out_unlock;
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	if (de->inode) {
		printf("this is %s(): %d >>> rec_len = %d\r\n", __func__, __LINE__, rec_len);
		printf("this is %s(): %d >>> name_len = %d\r\n", __func__, __LINE__, name_len);
		printf("this is %s(): %d >>> de = %x\r\n", __func__, __LINE__, de);
		ext2_dirent *de1 = (ext2_dirent *) ((char *) de + name_len);
		de1->rec_len = ext2_rec_len_to_disk(rec_len - name_len);
		printf("this is %s(): %d >>> de1 = %x\r\n", __func__, __LINE__, de1);
		de->rec_len = ext2_rec_len_to_disk(name_len);
		g_de = de;
		printf("this is %s(): %d >>> de->rec_len = %d\r\n", __func__, __LINE__, de->rec_len);
		printf("this is %s(): %d >>> de1->rec_len = %d\r\n", __func__, __LINE__, de1->rec_len);
		de = de1;
	}
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	de->name_len = namelen;
	printf("this is %s(): %d >>> name = %s\r\n", __func__, __LINE__, name);
	printf("this is %s(): %d >>> namelen = %d\r\n", __func__, __LINE__, namelen);
	memcpy(de->name, name, namelen);
	de->inode = cpu_to_le32(inode->i_ino);
	ext2_set_de_type (de, inode);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	err = ext2_commit_chunk(page, pos, rec_len);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	// dir->i_mtime = dir->i_ctime = CURRENT_TIME_SEC;
	// EXT2_I(dir)->i_flags &= ~EXT2_BTREE_FL;
	// mark_inode_dirty(dir);
	/* OFFSET_CACHE */
out_put:
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	// ext2_put_page(page);
out:
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	return err;
out_unlock:
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	// unlock_page(page);
	goto out_put;
}

int ext2_make_empty(struct inode *inode, struct inode *parent)
{
	struct address_space *mapping = inode->i_mapping;
	struct page *page = grab_cache_page(mapping, 0);
	unsigned chunk_size = ext2_chunk_size(inode);
	struct ext2_dir_entry_2 * de;
	int err;
	void *kaddr;

	printf("this is %s(): %d\r\n", __func__, __LINE__);

	if (!page)
		return -ENOMEM;

	printf("this is %s(): %d\r\n", __func__, __LINE__);
	err = __ext2_write_begin(NULL, page->mapping, 0, chunk_size, 0,
							&page, NULL);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	if (err) {
		// unlock_page(page);
		goto fail;
	}
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	kaddr = kmap_atomic(page, KM_USER0);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	memset(kaddr, 0, chunk_size);
	de = (struct ext2_dir_entry_2 *)kaddr;
	de->name_len = 1;
	de->rec_len = ext2_rec_len_to_disk(EXT2_DIR_REC_LEN(1));
	memcpy (de->name, ".\0\0", 4);
	de->inode = cpu_to_le32(inode->i_ino);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	ext2_set_de_type (de, inode);
	printf("this is %s(): %d\r\n", __func__, __LINE__);

	de = (struct ext2_dir_entry_2 *)(kaddr + EXT2_DIR_REC_LEN(1));
	de->name_len = 2;
	de->rec_len = ext2_rec_len_to_disk(chunk_size - EXT2_DIR_REC_LEN(1));
	de->inode = cpu_to_le32(parent->i_ino);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	memcpy (de->name, "..\0", 4);
	ext2_set_de_type (de, inode);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	kunmap_atomic(kaddr, KM_USER0);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	err = ext2_commit_chunk(page, 0, chunk_size);
	printf("this is %s(): %d\r\n", __func__, __LINE__);
fail:
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	// page_cache_release(page);
	return err;
}

struct ext2_dir_entry_2 *ext2_find_entry(struct inode * dir,
			struct qstr *child, struct page ** res_page)
{
	const char *name = child->name;
	int namelen = child->len;
	unsigned reclen = EXT2_DIR_REC_LEN(namelen);
	unsigned long start, n;
	unsigned long npages = dir_pages(dir);
	struct page *page = NULL;
	struct ext2_inode_info *ei = EXT2_I(dir);
	ext2_dirent * de;
	int dir_has_error = 0;

	if (npages == 0)
		goto out;

	/* OFFSET_CACHE */
	*res_page = NULL;

	start = ei->i_dir_start_lookup;
	if (start >= npages)
		start = 0;
	n = start;
	do {
		char *kaddr;
		page = ext2_get_page(dir, n, dir_has_error);
		if (!IS_ERR(page)) {
			kaddr = page_address(page);
			de = (ext2_dirent *) kaddr;
			kaddr += ext2_last_byte(dir, n) - reclen;
			while ((char *) de <= kaddr) {
				if (de->rec_len == 0) {
					ext2_error(dir->i_sb, __func__,
						"zero-length directory entry");
					// ext2_put_page(page);
					goto out;
				}
				if (ext2_match (namelen, name, de))
					goto found;
				de = ext2_next_entry(de);
			}
			// ext2_put_page(page);
		} else
			dir_has_error = 1;

		if (++n >= npages)
			n = 0;
		/* next page is past the blocks we've got */
		if ((n > (dir->i_blocks >> (PAGE_CACHE_SHIFT - 9)))) {
			ext2_error(dir->i_sb, __func__,
				"dir %lu size %lld exceeds block count %llu",
				dir->i_ino, dir->i_size,
				(unsigned long long)dir->i_blocks);
			goto out;
		}
	} while (n != start);
out:
	return NULL;

found:
	*res_page = page;
	ei->i_dir_start_lookup = n;
	return de;
}

ino_t ext2_inode_by_name(struct inode *dir, struct qstr *child)
{
	ino_t res = 0;
	struct ext2_dir_entry_2 *de;
	struct page *page;
	
	de = ext2_find_entry(dir, child, &page);
	if (de) {
		res = le32_to_cpu(de->inode);
		// ext2_put_page(page);
	}
	return res;
}

static unsigned char ext2_filetype_table[EXT2_FT_MAX] = {
	[EXT2_FT_UNKNOWN]	= DT_UNKNOWN,
	[EXT2_FT_REG_FILE]	= DT_REG,
	[EXT2_FT_DIR]		= DT_DIR,
	[EXT2_FT_CHRDEV]	= DT_CHR,
	[EXT2_FT_BLKDEV]	= DT_BLK,
	[EXT2_FT_FIFO]		= DT_FIFO,
	[EXT2_FT_SOCK]		= DT_SOCK,
	[EXT2_FT_SYMLINK]	= DT_LNK,
};

static int ext2_readdir(struct file * filp, void * dirent, filldir_t filldir)
{
	loff_t pos = filp->f_pos;
	struct inode *inode = filp->f_path.dentry->d_inode;
	struct super_block *sb = inode->i_sb;
	unsigned int offset = pos & ~PAGE_CACHE_MASK;
	unsigned long n = pos >> PAGE_CACHE_SHIFT;
	unsigned long npages = dir_pages(inode);
	unsigned chunk_mask = ~(ext2_chunk_size(inode)-1);
	unsigned char *types = NULL;
	int need_revalidate = filp->f_version != inode->i_version;

	printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
	printf("this is %s(): %d\r\n", __func__, __LINE__);

	if (pos > inode->i_size - EXT2_DIR_REC_LEN(1))
		return 0;
	printf("this is %s(): %d\r\n", __func__, __LINE__);

	if (EXT2_HAS_INCOMPAT_FEATURE(sb, EXT2_FEATURE_INCOMPAT_FILETYPE))
		types = ext2_filetype_table;

	for ( ; n < npages; n++, offset = 0) {
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		char *kaddr, *limit;
		ext2_dirent *de;
		struct page *page = ext2_get_page(inode, n, 0);
		printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);

		if (IS_ERR(page)) {
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			ext2_error(sb, __func__,
				   "bad page in #%lu",
				   inode->i_ino);
			filp->f_pos += PAGE_CACHE_SIZE - offset;
			return PTR_ERR(page);
		}
		printf("this is %s(): %d\r\n", __func__, __LINE__);
		kaddr = page_address(page);
		printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
		// if (unlikely(need_revalidate)) {
		// 	if (offset) {
		// 		offset = ext2_validate_entry(kaddr, offset, chunk_mask);
		// 		filp->f_pos = (n<<PAGE_CACHE_SHIFT) + offset;
		// 	}
		// 	filp->f_version = inode->i_version;
		// 	need_revalidate = 0;
		// }
		de = (ext2_dirent *)(kaddr+offset);
		limit = kaddr + ext2_last_byte(inode, n) - EXT2_DIR_REC_LEN(1);
		for ( ;(char*)de <= limit; de = ext2_next_entry(de)) {
			printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
			printf("this is %s(): %d >>> limit = %x\r\n", __func__, __LINE__, limit);
			printf("this is %s(): %d >>> de = %x\r\n", __func__, __LINE__, de);
			printf("this is %s(): %d >>> ext2_next_entry(de) = %x\r\n", __func__, __LINE__, ext2_next_entry(de));
			printf("this is %s(): %d >>> de->name = %s\r\n", __func__, __LINE__, de->name);
			if (de->rec_len == 0) {
				printf("this is %s(): %d\r\n", __func__, __LINE__);
				ext2_error(sb, __func__,
					"zero-length directory entry");
				// ext2_put_page(page);
				return -EIO;
			}
			if (de->inode) {
				printf("this is %s(): %d\r\n", __func__, __LINE__);
				int over;
				unsigned char d_type = DT_UNKNOWN;

				if (types && de->file_type < EXT2_FT_MAX)
					d_type = types[de->file_type];

				offset = (char *)de - kaddr;
#if 0
				over = filldir(dirent, de->name, de->name_len,
						(n<<PAGE_CACHE_SHIFT) | offset,
						le32_to_cpu(de->inode), d_type);
				if (over) {
					// ext2_put_page(page);
					return 0;
				}
#else
				printf("this is %s(): %d >>> de->name = %s\r\n", __func__, __LINE__, de->name);
				strcpy(((struct dirents *)dirent)->dirent->d_name, de->name);
				((struct dirents *)dirent)->num++;
				((struct dirents *)dirent)->dirent++;
#endif
			}
			filp->f_pos += ext2_rec_len_from_disk(de->rec_len);
			printf("this is %s(): %d\r\n", __func__, __LINE__);
			printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
		}
		// ext2_put_page(page);
		printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
		printf("this is %s(): %d\r\n", __func__, __LINE__);
	}
	printf("this is %s(): %d\r\n", __func__, __LINE__);
	printf("this is %s(): %d >>> g_de->rec_len = %d\r\n", __func__, __LINE__, g_de->rec_len);
	return 0;
}

const struct file_operations ext2_dir_operations = {
	// .llseek		= generic_file_llseek,
	// .read		= generic_read_dir,
	.readdir	= ext2_readdir,
	// .unlocked_ioctl = ext2_ioctl,
// #ifdef CONFIG_COMPAT
	// .compat_ioctl	= ext2_compat_ioctl,
// #endif
	// .fsync		= simple_fsync,
};
